package cn.nebula.music.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.nebula.music.domain.User;

public class LoginInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		User user = (User) request.getSession().getAttribute("USER");
		if (user != null) { // 这个方法返回false表示忽略当前请求，如果一个用户调用了需要登录才能使用的接口，如果太没有登录这里会直接忽略掉
			request.getSession().setAttribute("user", user);
			return true;
		} // 不符合条件的给出提示信息，并转发到登录页面

		request.setAttribute("msg", "您还没有登录，请先登录！");
		request.getRequestDispatcher("/").forward(request, response);
		return false;

	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			@Nullable ModelAndView modelAndView) throws Exception {
		System.out.println("LoginInterceptor.......postHandle");
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
			@Nullable Exception ex) throws Exception {
		System.out.println("LoginInterceptor.......afterCompletion");
	}

}
